package org.turman.buobaobook.component;


import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 这是一个手动配置定时任务的示例
 */

@Component
public class QuartzInitializer implements ApplicationListener<ApplicationReadyEvent> {

    private final Scheduler scheduler;
    private final JobDetail bookDownloadJobDetail;
    private final Trigger bookDownloadTrigger;

    @Autowired
    public QuartzInitializer(Scheduler scheduler, JobDetail bookDownloadJobDetail, Trigger bookDownloadTrigger) {
        this.scheduler = scheduler;
        this.bookDownloadJobDetail = bookDownloadJobDetail;
        this.bookDownloadTrigger = bookDownloadTrigger;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            if (scheduler.checkExists(bookDownloadJobDetail.getKey())) {
                scheduler.deleteJob(bookDownloadJobDetail.getKey());
            }

            scheduler.scheduleJob(bookDownloadJobDetail, bookDownloadTrigger);
            System.out.println("Job and Trigger have been manually scheduled.");
        } catch (SchedulerException e) {
            System.err.println("Failed to schedule job and trigger manually: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
